<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="JVM," />










<meta name="description" content="前言最近在B站上学习子烁老师的垃圾回收机制篇，讲的很清晰，这里根据自己理解写下笔记加深下印象。 下面主要以垃圾回收基础知识、回收算法、分代回收策略、经典垃圾收集器四个方面展开。  垃圾回收基础主要回收的垃圾是什么首先我们要搞清楚我们主要回收的垃圾是什么，这边我们需要了解Java虚拟机内内存是怎么分布的，这些内存分别存储了什么东西，下图是JVM的内存模型：  红色框：代表的是线程私有的内存，这些内存">
<meta property="og:type" content="article">
<meta property="og:title" content="JVM垃圾回收机制">
<meta property="og:url" content="http://yoursite.com/p/18011a7d.html">
<meta property="og:site_name" content="Molzhao">
<meta property="og:description" content="前言最近在B站上学习子烁老师的垃圾回收机制篇，讲的很清晰，这里根据自己理解写下笔记加深下印象。 下面主要以垃圾回收基础知识、回收算法、分代回收策略、经典垃圾收集器四个方面展开。  垃圾回收基础主要回收的垃圾是什么首先我们要搞清楚我们主要回收的垃圾是什么，这边我们需要了解Java虚拟机内内存是怎么分布的，这些内存分别存储了什么东西，下图是JVM的内存模型：  红色框：代表的是线程私有的内存，这些内存">
<meta property="og:image" content="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/2021/2021-01-19/JVM%E5%86%85%E5%AD%98%E6%A8%A1%E5%9E%8B.png">
<meta property="og:image" content="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/2021/2021-01-19/%E5%BC%95%E7%94%A8%E8%AE%A1%E6%95%B0%E5%99%A8.png">
<meta property="og:image" content="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/2021/2021-01-19/%E5%BC%95%E7%94%A8%E8%AE%A1%E6%95%B0%E5%99%A8-%E5%BE%AA%E7%8E%AF%E5%BC%95%E7%94%A8.png">
<meta property="og:image" content="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/2021/2021-01-19/%E5%8F%AF%E8%BE%BE%E6%80%A7%E7%AE%97%E6%B3%95.png">
<meta property="og:image" content="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/2021/2021-01-19/%E6%A0%87%E8%AE%B0-%E6%B8%85%E9%99%A4.png">
<meta property="og:image" content="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/2021/2021-01-19/%E5%A4%8D%E5%88%B6%E7%AE%97%E6%B3%95.png">
<meta property="og:image" content="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/2021/2021-01-19/%E6%A0%87%E8%AE%B0-%E6%95%B4%E7%90%86.png">
<meta property="og:image" content="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/2021/2021-01-19/Heap.png">
<meta property="og:image" content="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/2021/2021-01-19/Minor%20GC1.png">
<meta property="og:image" content="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/2021/2021-01-19/Minor%20GC2.png">
<meta property="og:image" content="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/Common/WeChat.png">
<meta property="article:published_time" content="2021-01-19T15:12:00.000Z">
<meta property="article:modified_time" content="2021-02-06T12:53:51.142Z">
<meta property="article:author" content="MolZhao">
<meta property="article:tag" content="JVM">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/2021/2021-01-19/JVM%E5%86%85%E5%AD%98%E6%A8%A1%E5%9E%8B.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"我们没有找到任何搜索结果: ${query}","hits_stats":"找到约${hits}条结果 (用时 ${time}ms)"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/p/18011a7d.html"/>





  <title>JVM垃圾回收机制 | Molzhao</title>
  








<meta name="generator" content="Hexo 4.2.1"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Molzhao</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>

                

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/p/18011a7d.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="MolZhao">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Molzhao">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">JVM垃圾回收机制</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2021-01-19T23:12:00+08:00">
                2021-01-19
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/JAVA/index.html" itemprop="url" rel="index">
                    <span itemprop="name">JAVA</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/p/18011a7d.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/p/18011a7d.html" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i> 阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2.9k 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  9 分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>最近在B站上学习<a href="https://www.bilibili.com/video/BV13T4y1N7oE" target="_blank" rel="noopener">子烁老师的垃圾回收机制篇</a>，讲的很清晰，这里根据自己理解写下笔记加深下印象。</p>
<p>下面主要以垃圾回收基础知识、回收算法、分代回收策略、经典垃圾收集器四个方面展开。</p>
<hr>
<h2 id="垃圾回收基础"><a href="#垃圾回收基础" class="headerlink" title="垃圾回收基础"></a>垃圾回收基础</h2><h3 id="主要回收的垃圾是什么"><a href="#主要回收的垃圾是什么" class="headerlink" title="主要回收的垃圾是什么"></a>主要回收的垃圾是什么</h3><p>首先我们要搞清楚我们主要回收的垃圾是什么，这边我们需要了解Java虚拟机内内存是怎么分布的，这些内存分别存储了什么东西，下图是JVM的内存模型：</p>
<p><img src="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/2021/2021-01-19/JVM%E5%86%85%E5%AD%98%E6%A8%A1%E5%9E%8B.png" alt="JVM内存模型"></p>
<p><font color = "red">红色框</font>：代表的是线程私有的内存，这些内存随着线程的创建而创建，销毁而销毁。<br><font color = "blue">蓝色框</font>：代表的是线程共享的内存。</p>
<p><strong>方法区：</strong>主要存储已经被虚拟机加载的类信息、常量、静态变量、即时编译器编译后的代码等。方法区主要回收的是废弃的常量和无用类。</p>
<p><strong>堆内存：</strong>就是存放对象实例，几乎所有的对象实例都在这里分配内存。主要回收无用的对象。</p>
<p>了解了上述这些之后我们知道，垃圾回收的主要区域在堆中。</p>
<hr>

<h3 id="垃圾何时被回收"><a href="#垃圾何时被回收" class="headerlink" title="垃圾何时被回收"></a>垃圾何时被回收</h3><p>当一个对象不再被引用了，也就是这个对象在内存中没有人用它的时候，这时候可以被回收。</p>
<p>这边引入一个概念，Java中的引用分为四类：</p>
<ol>
<li>强引用：如果一个对象具有强引用，它就不会被垃圾回收器回收。即使当前内存空间不足，JVM也不会回收它，而是抛出 OutOfMemoryError 错误，使程序异常终止。如果想中断强引用和某个对象之间的关联，可以显式地将引用赋值为null，这样一来的话，JVM在合适的时间就会回收该对象。强引用的创建最为常见一般<code>Object object = new Object();</code>就是强引用。</li>
<li>软引用：如果内存的空间足够，软引用就能继续被使用，而不会被垃圾回收器回收，只有在内存不足时，软引用才会被垃圾回收器回收。</li>
<li>弱引用：只要发生GC就会回收。</li>
<li>虚引用：在垃圾被回收时候可以接收一个通知</li>
</ol>
<hr>

<h3 id="判断垃圾是否可被回收"><a href="#判断垃圾是否可被回收" class="headerlink" title="判断垃圾是否可被回收"></a>判断垃圾是否可被回收</h3><p>判断一个垃圾是否被回收，那么我们就要确定他是否还有用。如何确定是否还有用呢，就是没有任何引用该对象，就说明这个对象是垃圾了，可以被回收。一般判断是否可以被回收，有两种算法：分别是<strong><em>引用计数法</em></strong>和<strong><em>可达性分析算法</em></strong></p>
<h4 id="引用计数法"><a href="#引用计数法" class="headerlink" title="引用计数法"></a>引用计数法</h4><p>引用计数法是通过引用计数器来判断对象是否存在引用，当有地方引用该对象时该对象的引用计数器就会加1，当引用失效就会减1。通过判断该对象的引用计数器是否为0来确定是否可被回收。如下图：<br><img src="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/2021/2021-01-19/%E5%BC%95%E7%94%A8%E8%AE%A1%E6%95%B0%E5%99%A8.png" alt="引用计数器"></p>
<p>但是我们仔细想想引用计数器他是存在问题的，如果两个无用的对象都引用了对方，那么他们的引用计数都为1，但却是垃圾对象。用了这个算法，GC永远无法回收下图中的A、B对象。<br><img src="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/2021/2021-01-19/%E5%BC%95%E7%94%A8%E8%AE%A1%E6%95%B0%E5%99%A8-%E5%BE%AA%E7%8E%AF%E5%BC%95%E7%94%A8.png" alt="引用计数-循环引用"></p>
<h4 id="可达性分析算法"><a href="#可达性分析算法" class="headerlink" title="可达性分析算法"></a>可达性分析算法</h4><p>该算法为主流GC发现垃圾对象的算法，它通过GC ROOT的对象作为搜索起始点，通过引用向下搜索，所走过的路径称为引用链。通过对象是否有到达引用链的路径来判断对象是否可被回收。<br><img src="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/2021/2021-01-19/%E5%8F%AF%E8%BE%BE%E6%80%A7%E7%AE%97%E6%B3%95.png" alt="可达性分析算法"></p>
<p>如上图所示，Object1–Object4对GC Root都是可达的，说明不可被回收，Object5–Object7对GC Root节点不可达，说明其可以被回收。</p>
<p>在Java中可以被作为GC Root对象的主要是下面四种：</p>
<ol>
<li>虚拟机栈（栈帧中的本地变量表）中引用的对象</li>
<li>方法区中类静态属性引用的对象</li>
<li>方法区中常量引用的对象</li>
<li>本地方法栈中JNI（即一般说的Native方法）引用的对象</li>
</ol>
<blockquote>
<p>即使在可达性分析算法中不可达的对象，非回收不可，这时候它们暂时处于“缓刑”阶段，要真正宣告一个对象死亡，至少要经历再次标记过程。<br>标记的前提是对象在进行可达性分析后发现没有与GC Roots相连接的引用链。<br><strong><em>第一次标记并进行一次筛选:</em></strong><br>筛选的条件是此对象是否有必要执行finalize()方法。<br>当对象没有覆盖finalize方法，或者finzlize方法已经被虚拟机调用过，虚拟机将这两种情况都视为没有必要执行，对象被回收。<br><strong><em>第二次标记:</em></strong><br>如果这个对象被判定为有必要执行finalize（）方法，那么这个对象将会被放置在一个名为：F-Queue的队列之中，并在稍后由一条虚拟机自动建立的、低优先级的Finalizer线程去执行。这里所谓的执行是指虚拟机会触发这个方法，但并不承诺会等待它运行结束。这样做的原因是，如果一个对象finalize（）方法中执行缓慢，或者发生死循环（更极端的情况），将很可能会导致F-Queue队列中的其他对象永久处于等待状态，甚至导致整个内存回收系统崩溃。<br>Finalize（）方法是对象脱逃死亡命运的最后一次机会，稍后GC将对F-Queue中的对象进行第二次小规模标记，如果对象要在finalize（）中成功拯救自己—-只要重新与引用链上的任何的一个对象建立关联即可，譬如把自己赋值给某个类变量或对象的成员变量，那在第二次标记时它将移除出“即将回收”的集合。如果对象这时候还没逃脱，那基本上它就真的被回收了。<br><a href="https://www.jianshu.com/p/8f5fa8288d9b" target="_blank" rel="noopener">原文链接</a></p>
</blockquote>
<hr>
<h2 id="回收算法"><a href="#回收算法" class="headerlink" title="回收算法"></a>回收算法</h2><p>由于JDK对垃圾收集器并没有制定规范，所以各个厂商都采用不同的方式来实现垃圾收集器，下面介绍四种主流的垃圾回收算法。</p>
<h3 id="标记-清除算法"><a href="#标记-清除算法" class="headerlink" title="标记-清除算法"></a>标记-清除算法</h3><p>该算法是最基础的收集算法。算法分为标记和清除两个阶段：首先标记出所有需要回收的对象，在标记完成后统一回收所有被标记的对象(标记过程主要是上述的可达性分析算法)。后续的收集算法都是基于这种思路并对其不足加以改进而已。</p>
<p><img src="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/2021/2021-01-19/%E6%A0%87%E8%AE%B0-%E6%B8%85%E9%99%A4.png" alt="标记-清除算法"></p>
<p><strong>严重问题：</strong><br>通过该算法回收的内存，会产生大量的内存碎片，由上图就很好理解，存活对象并不是在一块的，由此产生一块块分散的未使用内存空间，会导致无法申请一个<font color = "red">比较大</font>的<font color = "red">连续</font>的内存空间。</p>
<hr>

<h3 id="复制算法"><a href="#复制算法" class="headerlink" title="复制算法"></a>复制算法</h3><p>该算法是为了解决<code>标记-清除</code>的内存碎片问题。它将可用内存按容量划分为大小相等的两块，每次只使用其中一块。当这块内存需要进行垃圾回收时，会将此区域还存活着的对象复制到另一块上面，然后再把已经使用过的内存区域一次清理掉。这样做的好处是每次都是对整个半区进行内存回收，内存分配时也就不需要考虑内存碎片等的复杂情况，只需要移动堆顶指针，按顺序分配即可。该算法逻辑清晰，也运行高效。</p>
<p><img src="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/2021/2021-01-19/%E5%A4%8D%E5%88%B6%E7%AE%97%E6%B3%95.png" alt="复制算法"></p>
<p><strong>严重问题：</strong><br>该算法必须把内存拆分为两半，意味着原本只需要10G的内存就能跑的程序，现在需要20G内存。需要的内存是原来的<font color = "red">两倍</font></p>
<hr>

<h3 id="标记-整理算法"><a href="#标记-整理算法" class="headerlink" title="标记-整理算法"></a>标记-整理算法</h3><p>由于复制收集算法在对象存活率较高时会进行比较多的复制操作，效率会变低。因此在存活率较高的老年代一般不能使用复制算法。</p>
<p>针对老年代的特点，提出了一种称之为<code>标记-整理算法</code>。标记过程仍与<code>标记-清除</code>过程一致，但后续步骤不是直接对可回收对象进行清理，而是让所有存活对象向一端移动，然后直接清理掉端边界以外的内存。</p>
<p><img src="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/2021/2021-01-19/%E6%A0%87%E8%AE%B0-%E6%95%B4%E7%90%86.png" alt="标记-整理算法"></p>
<p><strong>严重问题：</strong><br>该算法存在<font color = "red">效率</font>的问题，内存变动更加频繁，每次都需要整理所有存活对象的引用地址。</p>
<hr>

<h3 id="分代收集算法"><a href="#分代收集算法" class="headerlink" title="分代收集算法"></a>分代收集算法</h3><p>这个算法没有新创意,只是上面三种算法的一套组合拳一般是把Java堆分为<font color = "red">新生代</font>和<font color = "red">老年代</font>。</p>
<p><img src="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/2021/2021-01-19/Heap.png" alt="Heap"></p>
<p>在新生代中，每次垃圾回收都有大批对象死去，只有少量存活，因此我们采用<code>复制算法</code>；而老年代中对象存活率高、没有额外空间对它进行分配担保，就必须采用<code>标记-清除</code>或者<code>标记-整理</code>算法。</p>
<hr>
<h2 id="分代回收策略"><a href="#分代回收策略" class="headerlink" title="分代回收策略"></a>分代回收策略</h2><p>当前JVM垃圾收集都采用的是<code>分代收集(Generational Collection)</code>算法，在Java堆中新生代默认是占堆的1/3，而老年代默认占堆的2/3</p>
<h3 id="新生代回收"><a href="#新生代回收" class="headerlink" title="新生代回收"></a>新生代回收</h3><p>所有新的对象基本都在Eden区中生成，等到Eden区被填满的时候就触发<font color = "red">Minor GC</font>，在Eden区中对象的存活率低，于是采用复制算法，将Eden区中存活对象复制到任意一个Survivor区中，再将Eden区清空，就完成了一次<font color = "red">Minor GC</font>。具体如下图：</p>
<p><img src="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/2021/2021-01-19/Minor%20GC1.png" alt="MinorGC1"></p>
<p>当Eden区再次被填满的时候，需要在进行一次<font color = "red">Minor GC</font>，但是之前的Survivor区中的对象不一定都是存活的，也会有一些垃圾对象，他也会在这次<font color = "red">Minor GC</font>中被清除。依旧采用的是复制算法，将Eden区和一个Survivor区中的存活对象复制到另一个Survivor区钟，在对另外两个区进行清除。</p>
<p><img src="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/2021/2021-01-19/Minor%20GC2.png" alt="MinorGC2"></p>
<p>接下来的每次<font color = "red">Minor GC</font>都和上面的流程一样，每次都需要清扫一个Eden区和一个Survivor区。</p>
<p><strong><em>Q1:对象什么时候从新生代进入老年代？</em></strong><br>新生代的每一次Minor GC都会使存活对象的年龄加1，也就是存活对象的复制次数。当年龄到达一个阈值的时候，该对象就会被放入老年代，这个阈值默认是15。</p>
<p><strong><em>Q2:进入老年代的方式有哪些？</em></strong><br>1.如果Minnor GC的存活对象比Survivor区大，那么这些对象会过早老化，直接进入老年带<br>2.经历15次Minor GC的对象<br>3.大数组，大字符串等会直接在老年代中进行创建。</p>
<p><strong><em>Q3:分代年龄可否设置成31？</em></strong><br>因为分代年龄在对象中占4位，4位二进制最大是15，因此不能设置成31。</p>
<hr>
<h3 id="老年代回收"><a href="#老年代回收" class="headerlink" title="老年代回收"></a>老年代回收</h3><p>由于老年代的GC频率较低，通常使用<code>标记-整理</code>算法来进行回收，老年代的回收又称为<font color = "red">Major GC</font>。</p>
<hr>
<blockquote>
<p>如果有小伙伴，想要一起交流学习的，欢迎添加博主微信。</p>
</blockquote>
<p><img src="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/Common/WeChat.png" alt="weChat"></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/JVM/index.html" rel="tag"># JVM</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/p/93bb270a.html" rel="next" title="Markdown引入Echarts">
                <i class="fa fa-chevron-left"></i> Markdown引入Echarts
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/p/5b25d7d2.html" rel="prev" title="HotSpot经典垃圾收集器(1)">
                HotSpot经典垃圾收集器(1) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="MolZhao" />
            
              <p class="site-author-name" itemprop="name">MolZhao</p>
              <p class="site-description motion-element" itemprop="description">沉淀</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/index.html">
              
                  <span class="site-state-item-count">54</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">30</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/normcorer" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:MolZhaovo@163.com" target="_blank" title="Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#垃圾回收基础"><span class="nav-number">2.</span> <span class="nav-text">垃圾回收基础</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#主要回收的垃圾是什么"><span class="nav-number">2.1.</span> <span class="nav-text">主要回收的垃圾是什么</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#垃圾何时被回收"><span class="nav-number">2.2.</span> <span class="nav-text">垃圾何时被回收</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#判断垃圾是否可被回收"><span class="nav-number">2.3.</span> <span class="nav-text">判断垃圾是否可被回收</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#引用计数法"><span class="nav-number">2.3.1.</span> <span class="nav-text">引用计数法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#可达性分析算法"><span class="nav-number">2.3.2.</span> <span class="nav-text">可达性分析算法</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#回收算法"><span class="nav-number">3.</span> <span class="nav-text">回收算法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#标记-清除算法"><span class="nav-number">3.1.</span> <span class="nav-text">标记-清除算法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#复制算法"><span class="nav-number">3.2.</span> <span class="nav-text">复制算法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#标记-整理算法"><span class="nav-number">3.3.</span> <span class="nav-text">标记-整理算法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#分代收集算法"><span class="nav-number">3.4.</span> <span class="nav-text">分代收集算法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#分代回收策略"><span class="nav-number">4.</span> <span class="nav-text">分代回收策略</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#新生代回收"><span class="nav-number">4.1.</span> <span class="nav-text">新生代回收</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#老年代回收"><span class="nav-number">4.2.</span> <span class="nav-text">老年代回收</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2024</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">MolZhao</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">ZYJ</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>






        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i> 访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i> 总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script type="text/javascript" src="/js/src/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: '18BuKzLQMbUp8ECwDBiHu6Df-MdYXbMMI',
        appKey: 'xVTsu5pYLayqSvClr36TzcAH',
        placeholder: '(•̀へ•╮)',
        avatar:'identicon',
        guest_info:guest,
        pageSize:'10' || 10,
    });

    $('.vpower').html('');
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "./public/search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "default";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
      flOptions = {};
      
          flOptions.iconStyle = "default";
      
          flOptions.boxForm = "horizontal";
      
          flOptions.position = "middleRight";
      
          flOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>

  

  

  

  

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"scale":1,"hHeadPos":0.5,"vHeadPos":0.5,"jsonPath":"/live2dw/assets/assets/wanko.model.json"},"display":{"superSample":2,"width":150,"height":150,"position":"right","hOffset":30,"vOffset":20},"mobile":{"show":false,"scale":0.05},"react":{"opacityDefault":0.6,"opacityOnHover":0.2},"log":false});</script></body>
</html>
